<template>
	<van-form :model="form" style="margin-top: 150px;">
		<h3 style="text-align: center;">新用户注册</h3>
		<van-field v-model="form.phone" name="" label="手机号" placeholder="请输入手机号"
			:rules="[{ required: true, message: '请填写手机号' }]" />
		<van-field v-model="form.code" label="验证码" placeholder="请输入验证码" use-button-slot>
			<van-button slot="button" size="small" type="danger" @click="getCode()">
				获取验证码
			</van-button>
		</van-field>
		<van-field v-model="form.password" type="password" name="" label="密码" placeholder="请输入密码" />
		<van-field v-model="form.password2" type="password" name="" label="确认密码" placeholder="请再次输入密码" />
		<div style="margin: 16px;">
			<van-button round block type="primary" @click="register()">立即注册</van-button>
			<br><br>
			<div style="font-size: 12px; text-align: center;  color:crimson" @click="toLogin">已有账号，去登录</div>
		</div>
	</van-form>

</template>

<script>
	import axios from "axios"

	export default {
		data() {
			return {
				form: {
					password2: '',
				},
				code: '',
				phone: []
			}
		},
		created() {
			axios.post(`http://localhost:10086/user/findAllPhone`).then(res => {
				this.phone = res.data;
			})
		},
		methods: {
			getCode() {
				// 验证手机号是否为空或null
				if (this.form.phone === "" || this.form.phone === null) {
					this.$message.error("请输入手机号");
					return;
				}
				// 验证手机号长度是否为11位
				if (this.form.phone.length !== 11) {
					this.$message.error("请输入有效手机号码（11位格式）");
					return;
				}
				// 检查手机号是否已注册
				for (let i = 0; i < this.phone.length; i++) {
					if (this.phone[i].phone === this.form.phone) {
						this.$message.error("该手机号已注册");
						return; // 找到已注册手机号，直接返回，不再执行后续请求发送操作
					}
				}
				// 发送获取验证码请求
				axios
					.post(`http://localhost:10086/user/sendCode/${this.form.phone}`)
					.then((res) => {
						console.log(res.data);
						this.code = res.data.code;
						this.$message.success("验证码已发送");
					})
					.catch((error) => {
						// 根据具体的接口返回错误格式等情况，给出合适的提示给用户
						this.$message.error("获取验证码失败，请稍后重试");
						console.error(error);
					});
			},
			toLogin() {
				location.href = "#/login";
			},
			register() {
				console.log(this.code);
				if (this.code != this.form.code) {
					this.$message.error("验证码错误");
				} else if (this.form.password2 != this.form.password) {
					this.$message.error("两次输入密码不一致");
				} else {
					axios.post(`http://localhost:10086/user/register`, this.form).then(res => {
						console.log(res);
						if (res.status == 200) {
							this.$message.success("注册成功");
							location.href = "#/login"
						} else {
							this.$message.error("注册失败");
						}
					})
				}
			},
		},
	}
</script>

<style>
</style>